#include "EchoServer.h"

EchoServer::EchoServer(const std::string &ip, const uint16_t port, int subThreadNum, int workThreadNum)
 : tcpServer_(ip, port, subThreadNum),threadPool_(workThreadNum, "WORKS")
{
    tcpServer_.set_new_Connection_Cb_(std::bind(&EchoServer::Handle_New_Connection, this, std::placeholders::_1));
    tcpServer_.set_close_Connection_Cb_(std::bind(&EchoServer::Handle_Close_Connection, this, std::placeholders::_1));
    tcpServer_.set_error_Connection_Cb_(std::bind(&EchoServer::Handle_Error_Connection, this, std::placeholders::_1));
    tcpServer_.set_on_Message_Cb_(std::bind(&EchoServer::Handle_On_Message, this, std::placeholders::_1, std::placeholders::_2));
    tcpServer_.set_send_Complete_Cb_(std::bind(&EchoServer::Handle_Send_Complete, this, std::placeholders::_1));
    tcpServer_.set_timeout_Cb_(std::bind(&EchoServer::Handle_Epoll_TimeOut, this, std::placeholders::_1));
}

EchoServer::~EchoServer()
{
    
}

void EchoServer::Start()
{
    tcpServer_.start();
}

void EchoServer::Stop()    //停止服务
{
    //停止工作线程
    threadPool_.stop();
    printf("工作线程已停止\n");
    //停止IO线程(事件循环) 
    tcpServer_.stop();
}

void EchoServer::Handle_New_Connection(spConnection conn)
{
    printf("%s new Connection.(fd = %d,ip = %s,port = %d)ok\n",Timestamp::now().toString().c_str(), conn->fd(),
    conn->ip().c_str(), conn->port());
    //printf("EchoServer::Handle_New_Connection thread is %ld.\n", syscall(SYS_gettid));
    // std::cout << "New Connection Come in." << std::endl;
    //业务逻辑
}

void EchoServer::Handle_Close_Connection(spConnection conn)
{
    printf("%s Connection closed.(fd = %d,ip = %s,port = %d)ok\n",Timestamp::now().toString().c_str(), conn->fd(),
    conn->ip().c_str(), conn->port());
    // std::cout << "EchoServer conn closed." << std::endl;
}

void EchoServer::Handle_Error_Connection(spConnection conn)
{
    // std::cout << "EchoServer conn error." << std::endl;
}

void EchoServer::Handle_On_Message(spConnection conn, std::string& message)
{
    //printf("EchoServer::Handle_On_Message thread is %ld.\n", syscall(SYS_gettid));
/*
    message = "reply:" + message;
    //把临时缓冲区的数据发生出去
    conn->send(message.data(), message.size());
*/
    if(threadPool_.size() == 0)
    {
        //如果没有工作线程，在IO线程处理业务
        OnMessage(conn, message);
    }
    else
    {
        //把业务添加到线程池任务队列中
        threadPool_.addtask(std::bind(&EchoServer::OnMessage, this, conn, message));
    }
}

void EchoServer::OnMessage(spConnection conn, std::string& message)
{
    // printf("%s recv(eventfd = %d):%s\n", Timestamp::now().toString().c_str(), conn->fd(), message.c_str());
    
    message = "reply:" + message;
    //把临时缓冲区的数据发生出去
    conn->send(message.data(), message.size());
}

void EchoServer::Handle_Send_Complete(spConnection conn)
{
    // std::cout << "Message send complete." << std::endl;
}

void EchoServer::Handle_Epoll_TimeOut(EventLoop *loop)
{
    // std::cout << "EchoServer timeout." << std::endl;
}

